# find the best lambda-power transformation for a given distribution fit
# use either:
# findlambda.ks()
# findlambda.distance()
# findlambda.correlation()

test.distance <- function(X, cdf) {
	d1 <- (1:length(X))/length(X)
	d2 <- cdf(sort(X))
	max((d1 - d2)^2)
}

find_lambda <- function(X, cdf, fit_test, best_fit)
{
	lambdas <- seq(-2,1.2,0.1)
	ps <- sapply(lambdas, function(lambda) fit_test(power_transform(X,lambda), cdf))
	lambda <- lambdas[which(best_fit(ps) == ps)[1]]

	lambdas <- lambda + (c(0,lambdas)/10)
	ps <- sapply(lambdas, function(lambda) fit_test(power_transform(X,lambda), cdf))
	fit <- best_fit(ps)
	lambda <- lambdas[which(fit == ps)[1]]

	data.frame(lambda=lambda, fit=fit)
}

